export default {
    name: "templateEditor",
    setup() {
        const library = [
            { 
                type: 'carousel', 
                name: '轮播图', 
                icon: 'Picture',
                config: {
                    items: []
                }
            },
            {
                type: 'notice',
                name: '滚动公告',
                icon: 'MuteNotification',
                config: {
                    text: '',
                    speed: 100,
                    color: '#333',
                    bgColor: '#fffbe8'
                }
            },
            {
                type: 'menu-grid',
                name: '网格菜单',
                icon: 'Menu',
                config: {
                    items: [],
                    columns: 2,
                    iconSize: 40, //图片大小
                    txtSize: 19, //文字大小
                    rowGap: 12,
                    colGap: 8
                }
            },
            {
                type: 'custom-grid',
                name: 'win8瓷贴菜单',
                icon: 'PictureRounded',
                config: {
                    items: [],
                    columns: 2,
                    rowHeight: 100, // 每行基准高度
                    gap: 8         // 间距
                }
            },
            {
                type: 'search',
                name: '搜索框',
                icon: 'Search',
                config: {
                    placeholder: '请输入关键词',
                    radius: 8,
                    bgColor: '#ffffff'
                }
            },
            {
                type: 'video',
                name: '视频模块',
                icon: 'VideoPlay',
                config: {
                    videoUrl: 'https://zp.kzhgzs.cn/uploads/f95744edbe4fd60615311598340e7d82.mp4',
                }
            },
            {
                type: 'article-list',
                name: '文章推荐',
                icon: 'Document',
                config: {
                    num: 5,         // 显示数量
                    titleColor: '#303133', // 标题颜色
                    dateColor: '#909399',  // 日期颜色
                    items: [{}]
                }
            },
            {
                type: 'query-list',
                name: '查询列表',
                icon: 'Search',
                config: {
                    num: 5,                // 显示条数
                    titleColor: '#303133',  // 标题颜色
                    dateColor: '#909399',   // 日期颜色
                }
            }
        ];
        const components = reactive({
            library: library,
            canvasComponents: [],
            activeIndex: -1
        });
        // 模板配置
        const templateConfig = reactive({
            name: '我的模板',
            backgroundColor: '#ffffff',
            pagePadding: 16,
            is_enabled: true, //是否启用
        });
        
        // 克隆组件
        const cloneComponent = (orig) => {
            const newComp = reactive({
                ..._.cloneDeep(orig), //用cloneDeep深拷贝
                id: `comp_${Date.now()}_${Math.random().toString(36).slice(2)}`
            });
            newComp._isComponent = true;
            return newComp;
        };
            
        // 使用透明克隆体代替修改原样式    
        const handleDragStart = (evt) => {
            // 设置拖拽效果为移动
            if(evt.dataTransfer) {
                evt.dataTransfer.effectAllowed = 'move'
            }
            // 创建透明克隆体
            const ghost = evt.item.cloneNode(true)
            ghost.style.opacity = '0.5'
            ghost.style.position = 'absolute'
            ghost.style.pointerEvents = 'none'
            document.body.appendChild(ghost)
            // 设置拖拽图像偏移量
            const rect = evt.item.getBoundingClientRect()
            const offsetX = evt.clientX - rect.left
            const offsetY = evt.clientY - rect.top
            evt.dataTransfer?.setDragImage(ghost, offsetX, offsetY)
            // 在下一帧移除克隆体
            requestAnimationFrame(() => {
                document.body.removeChild(ghost)
            })
        };

        // 操作历史
        const history = reactive({
            stack: [],
            currentStep: -1
        });

        // 删除组件
        const deleteComponent = (index) => {
            components.canvasComponents.splice(index, 1);
            components.activeIndex = -1;
            saveHistory();
        };

        // 保存历史记录
        const saveHistory = () => {
            console.log('保存历史记录')
            history.stack = history.stack.slice(0, history.currentStep + 1);
            history.stack.push({
                components: _.cloneDeep(components.canvasComponents),
                config: _.cloneDeep(templateConfig)
            });
            history.currentStep++;
        };

        // 撤销操作
        const undo = () => {
            if (history.currentStep > 0) {
                history.currentStep--;
                applyHistoryState();
            }
        };

        // 重做操作
        const redo = () => {
            if (history.currentStep < history.stack.length - 1) {
                history.currentStep++;
                applyHistoryState();
            }
        };

        // 应用历史状态
        const applyHistoryState = () => {
            const state = history.stack[history.currentStep];
            components.canvasComponents = _.cloneDeep(state.components);
            Object.assign(templateConfig, state.config);
        };

        // 生成移动端配置
        const generateConfig = () => {
            return {
                ...templateConfig,
                components: components.canvasComponents.map(c => ({
                    type: c.type,
                    config: c.config
                }))
            };
        };

        // 保存模板
        const saveTemplate = async () => {
            const configData = generateConfig();
            await savehometemplate({
                name: configData.name,
                backgroundColor: configData.backgroundColor,
                pagePadding: configData.pagePadding,
                is_enabled: configData.is_enabled,
                components: configData.components
            });
            ElMessage.success('保存成功');
            await initTemplate(); // 重新加载最新数据
        };
        
        const handleAdd = (evt) => {
            console.log('跨组添加:', evt.item.__draggable_context.element);
            saveHistory(); // 直接保存状态
        };
        
        // 移动组件方法
        const moveComponent = (fromIndex, toIndex) => {
            const item = components.canvasComponents.splice(fromIndex, 1)[0]
            components.canvasComponents.splice(toIndex, 0, item)
            saveHistory()
        }
        
        const handleDragEnd = (evt) => {
            // 强制清除拖拽状态
            if(evt.dataTransfer) {
                evt.dataTransfer.dropEffect = 'move'
            }
            components.activeIndex = -1
            saveHistory()
        };
        
        // 添加菜单
        const addMenuItem = () => {
            if (components.activeIndex === -1 || componentType.value !== 'menu-grid') return;
            const newItem = {
                id: `menu_${Date.now()}_${Math.random().toString(36).slice(2)}`,
                name: `菜单${activeComponent.value.config.items.length + 1}`,
                image: '', // 初始化图片地址
                link: '/pages/index/index',
                type: 'navigate',
                customStyle: {}
            }
            activeComponent.value.config.items.push(newItem)
            saveHistory()
        }
        
        const removeMenuItem = (index) => {
            if (
                components.activeIndex === -1 || 
                componentType.value !== 'menu-grid'
            ) return
            activeComponent.value.config.items.splice(index, 1)
            saveHistory()
        }
        
        // 修改后的初始化逻辑
        const initTemplate = async () => {
            const res = await gethometemplate()
            console.log('原始数据:', res)
            // 重置模板配置
            Object.assign(templateConfig, {
                name: res.name,
                backgroundColor: res.backgroundColor,
                pagePadding: res.pagePadding,
                is_enabled: res.is_enabled
            })
            // 映射组件数据
            const mappedComponents = res.components.map(c => {
                const base = components.library.find(lib => lib.type === c.type);
                if (!base) {
                    console.warn(`未知组件类型: ${c.type}`)
                    return null
                }
                return {
                    ..._.cloneDeep(base),
                    id: `comp_${Date.now()}_${Math.random().toString(36).slice(2)}`,
                    config: _.merge({}, base.config, c.config)
                }
            }).filter(Boolean)
            console.log('映射后的组件:', mappedComponents)
            // 使用splice保持响应式
            components.canvasComponents.splice(0, components.canvasComponents.length, ...mappedComponents)
            // 重置历史记录
            history.stack = [{
                components: _.cloneDeep(mappedComponents),
                config: _.cloneDeep(templateConfig)
            }]
            history.currentStep = 0
            await nextTick()
        }

        onMounted(() => {
            initTemplate();
        })
                
        // 当前激活的组件
        const activeComponent = computed(() => {
            const index = components.activeIndex
            return index >= 0 && index < components.canvasComponents.length ? components.canvasComponents[index] : null;
        })
        
        // 组件类型判断
        const componentType = computed(() => activeComponent.value?.type);

        return {
            components,
            templateConfig,
            history,
            deleteComponent,
            undo,
            redo,
            saveTemplate,
            generateConfig,
            saveHistory,
            cloneComponent,
            handleDragStart,
            handleAdd,
            handleDragEnd,
            moveComponent,
            addMenuItem,
            removeMenuItem,
            activeComponent,
            componentType,
            initTemplate,
            draggableOptions: {
                animation: 200,
                forceFallback: true,  // 强制使用polyfill
                fallbackOptions: {
                    appendTo: 'body', // 优化拖拽层
                    scrollSensitivity: 100
                }
            }
        };
    },

    template: `
    <div class="template-editor">
        <!-- 顶部工具栏 -->
        <div class="toolbar">
            <el-button type="primary" @click="saveTemplate">保存模板</el-button>
            <el-button-group class="undo-redo">
                <el-button :disabled="history.currentStep <= 0" @click="undo">
                    <el-icon><RefreshLeft /></el-icon>撤销
                </el-button>
                <el-button :disabled="history.currentStep >= history.stack.length - 1" @click="redo">
                    重做<el-icon><RefreshRight /></el-icon>
                </el-button>
            </el-button-group>
        </div>

        <div class="editor-main">
            <!-- 组件库 -->
            <div class="component-library">
                <div class="title">组件库</div>
                <draggable :list="components.library" :group="{ name: 'diyGroup', pull: 'clone', put: false }" :clone="cloneComponent" @start="handleDragStart" @end="handleDragEnd" :force-fallback="true" :sort="false" item-key="type">
                    <template #item="{ element }">
                        <div class="component-item">
                            <el-icon><component :is="element.icon" /></el-icon>
                            <span style="margin-left: 10px;">{{ element.name }}</span>
                        </div>
                    </template>
                </draggable>
            </div>

            <!-- 画布区域 -->
            <ComponentPreview 
                v-model="components.canvasComponents"
                :template-config="templateConfig"
                :active-index="components.activeIndex"
                :draggable-options="draggableOptions"
                @update:active-index="val => components.activeIndex = val"
                @delete="deleteComponent"
                @drag-start="handleDragStart"
                @drag-end="handleDragEnd"
                @add="handleAdd"/>

            <!-- 属性配置面板 -->
            <PropertyPanel
                :template-config="templateConfig"
                :active-component="activeComponent"
                :active-index="components.activeIndex"
                :canvas-components="components.canvasComponents"
                @update:template-config="val => Object.assign(templateConfig, val)"
                @move-component="moveComponent"
                @add-menu-item="addMenuItem"
                @remove-menu-item="removeMenuItem"/>
                
        </div>
    </div>
    `
}